package com.hefan.common.sequence.service;

import com.hefan.common.sequence.dao.CodeSequenceDao;
import com.hefan.common.sequence.Coder;
import com.hefan.common.sequence.CoderType;
import com.hefan.common.sequence.SequenceGenerator;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author ninglijun
 * @description
 */
@Component("sequenceGenerator")
public class SequenceGeneratorImpl extends ApplicationObjectSupport implements SequenceGenerator {

    @Resource
    private CodeSequenceDao codeSequenceDao;

    @Override
    public String nextVal(CoderType coderType) {
        String codeTypeStr = coderType.name().toLowerCase();
        Coder coder = getApplicationContext().getBean(codeTypeStr + "Coder", Coder.class);
        if (coder == null) {
            throw new RuntimeException("No coder selected....");
        }
        long seq = codeSequenceDao.nextVal(coder.sequence());
        return coder.encode(null, seq);
    }
}